const initState = {
  CardList: []
}

export default (state = initState, action) => {
  
  if (action.type === 'INIT_TODO') {
    return {
      ...state,
      CardList: action.data
    }
  }

  if (action.type === 'ADD_TODO') {
    let newCardList = JSON.parse(JSON.stringify(state.CardList))
    let {id, name, price} = action.good
    // 判断仓库中是否存在要添加的商品，存在就++,不存在直接push
    let index = newCardList.findIndex(item => item.goodId === id)
    if (index > -1) {
      //表示存在
      newCardList[index].goodNum++
    } else {
      // 表示不存在
      newCardList.push({
        id: id,
        goodId: id,
        goodName: name,
        goodPrice: price,
        goodNum: 1
      })
    }
    return {
      ...state,
      CardList: newCardList
    }
  }

  if (action.type === 'DEL_TODO') {
    let newCardList = JSON.parse(JSON.stringify(state.CardList))
    let {id} = action.good
    // 判断仓库中是否存在要添加的商品，存在就--,不存在直接return出去
    let index = newCardList.findIndex(item => item.goodId === id)
    if (index <= -1) {
      // 表示不存在
      return state
    } 
    // 判断当前商品在购物车中购买数量是多少
    if (newCardList[index].goodNum === 1){
      newCardList.splice(index, 1)
    } else {
      // 做减减操作
      newCardList[index].goodNum--
    }
    return {
      ...state,
      CardList: newCardList
    }
  }
  return state
}